/*
 * @Descripttion: 
 * @Author: xiaodong
 * @Date: 2021-01-19 18:02:51
 * @LastEditTime: 2021-01-21 18:13:13
 * @FilePath: \cloud-monitor-server\src\model\parse\monitor_ext.js
 */
import moment from 'moment'
import Knex from '~/src/library/mysql'
import Logger from '~/src/library/logger'
import _ from "lodash";
const BASE_TABLE_NAME = 't_o_monitor_ext'

const TABLE_COLUMN = [
  `id`,
  `ext_json`,
  `create_time`,
  `update_time`
]

/**
 * @param {*} projectId
 * @param {*} visitAt
 */
function getTableName (projectId, visitAt) {
  let visitAtMonth = moment.unix(visitAt).format('YYYYMM')
  return `${BASE_TABLE_NAME}_${projectId}`//_${visitAtMonth}
}
async function insertMonitorExt(
  projectId,
  ext_json,
  createTime
) {
  const tableName = getTableName(projectId, createTime);
  const insertData = {
    ext_json: ext_json,
    create_time: createTime,
    update_time: createTime,
  };
  // console.log(insertData);
  // 首先插入城市分布数据
  //  let cityDistributeId = await MCityDistribution.insertCityDistributionRecord(JSON.stringify(cityDistribute), projectId, updateAt)
  //  if (cityDistributeId === 0) {
  //    // 城市分布数据插入失败
  //    return false
  //  }
  let insertResult = await Knex.insert(insertData, ["id"])
    .into(tableName)
    .catch(e => {
      return [];
    });
  return _.get(insertResult, [0], 0) > 0;
}
async function getRecordListByIdList (projectId, createAt, idList = []) {
  let tableName = getTableName(projectId, createAt)
  let rawRecordList = Knex
    .select(TABLE_COLUMN)
    .from(tableName)
    .whereIn('create_time', idList)
    .catch(e => {
      Logger.warn('getRecordListByIdList查询失败 => ', e)
      return []
    })
  return rawRecordList
}

export default {
  getTableName,
  insertMonitorExt,
  getRecordListByIdList
}
